package com.example.demo.pojo;

import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * @author luolinila
 */
@Data
public class Room implements Serializable {
    int roomId;
    Game game;
    HashSet<User> users;
    int state;

    public Room(int roomId) {
           this.roomId = roomId;
           this.game = new Game();
           this.users = new HashSet<>();
           this.state = 0;
    }

    //用户加入
    public int addUser(User user) {
        //对局开始时无法加入
        if(state == 1) {
            return -1;
        }
        //最大人数为6
        if (users.size() < 6) {
            users.add(user);
            //返回房间人数
            return users.size();
        }
        return -1;
    }

    //移除用户
    public int removeUser(User user) {
        if(users.isEmpty() || !users.contains(user) || state == 1) {
            return -1;
        }
        users.remove(user);
        return users.size();
    }

    //开始对局
    public int start() {
        List<Player> arr = new ArrayList<>();
        for (User user : users) {
            System.out.println(user.balance);
            arr.add(new Player(user));
        }
        //检验玩家筹码是否大于底注
        for (Player player : arr) {
            System.out.println(player.chip);
            if(player.chip <= 1) {
                return -1;
            }
        }
        //启动游戏
        game = new Game(arr);
        game.start();
        //发手牌
        game.faPaiPlayersAll();
        //更改标识
        state = 1;
        return 1;
    }

    //结束对局
    public void end() {
        game.end();
        // players -> users
        for (Player player: game.getPlayers()) {
            for (User user: users) {
                if(user.getUid() == player.getId()) {
                    user.balance = player.getChip();
                    break;
                }
            }
        }
        //更改标识
        state = 0;
    }

    //获取当前行动玩家id
    public int getActionUserId() {
        Player player = game.getActionPlayer();
        if(player != null) {
            return player.id;
        }
        return -1;
    }

    //跟注
    public int call() {
        return game.call();
    }

    //加注
    public int raise(String data) {
        String[] res = data.split("_");
        double raise = Double.parseDouble(res[1]);
        return game.raise(raise);
    }

    //AllIn
    public int allIn() {
        return game.allIn();
    }

    //弃牌
    public int fold() {
        //玩家弃牌
        Player outPlayer = game.fold();
        //outPlayer -> user
        for (User user : users) {
            if (user.uid == outPlayer.id) {
                user.balance = outPlayer.getChip();
                break;
            }
        }
        return game.players.size();
    }

    public void stop() {
        state = 0;
    }
}
